﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using HonStats.Heartbeat.Model;
using HonStats.Heartbeat.Library;
using System.Net;
using System.IO;
using System.Collections;
using System.Threading;

namespace HonStats.Heartbeat
{

    public class Scraper
    {
        public static volatile bool Running;
        private Thread SpawnThread;
        private int MaxUserID { get; set; }
        private int MaxThreads { get; set; }
        private static int CurrentUserID;
        private Parser StatsParser = new Parser();

        /// <summary>
        /// Default Scraper settings if none are provided
        /// </summary>
        public Scraper()
            : this(0, Int32.MaxValue, 25)
        {
        }
        
        public Scraper(int currentUserID, int MaxUserID, int MaxThreads)
        {
            CurrentUserID = currentUserID;
            this.MaxUserID = MaxUserID;
            this.MaxThreads = MaxThreads;
            Running = false;

           // ThreadPool.SetMaxThreads(MaxThreads, MaxThreads);
        }

        public void Start()
        {
            if (!Running)
            {
                Running = true;
                SpawnThread = new Thread(SpawnThreads);
                SpawnThread.Start();
            }
        }

        public void Stop()
        {
            if (Running == true)
            {
                Running = false;
                SpawnThread.Join();
            }
        }

        private void SpawnThreads()
        {
            int availableWorkerThreads;
            int availableCompletionThreads;
            int maxWorkerThreads;
            int maxCompletionThreads;

            while (Running)
            {
                ThreadPool.GetAvailableThreads(out availableWorkerThreads,out availableCompletionThreads);
                ThreadPool.GetMaxThreads(out maxWorkerThreads, out maxCompletionThreads);
                while ((maxWorkerThreads - availableWorkerThreads) < 10)
                {
                  //  Console.WriteLine("Used: {0}", maxWorkerThreads - availableWorkerThreads);
                    ThreadPool.QueueUserWorkItem(new WaitCallback(FetchNextStats));
                    Thread.Sleep(1);
                    ThreadPool.GetAvailableThreads(out availableWorkerThreads, out availableCompletionThreads);
                }
                Thread.Sleep(1);
            }

        }

        public static void FetchNextStats(object state)
        {
            for (int i = 0; i < 5; i++)
            {
                int currentUserID = Interlocked.Increment(ref CurrentUserID);
                Console.WriteLine("Fetching UserID: {0}", currentUserID);

                string userData = FetchStats(currentUserID);
                Console.WriteLine(userData);
                Console.WriteLine();
            }
        }

        public static string FetchStats(string Nick)
        {
            var rawUserID = GetUrlContents(String.Format("https://masterserver.hon.s2games.com/client_requester.php?f=nick2id&nickname[0]={0}", Nick));
           
            var serializer = new PHPSerializer();
            Hashtable deserializedUserInfo = (Hashtable)serializer.Deserialize(rawUserID);//Deserialize the Hashtable
            
            var UserID = deserializedUserInfo[Nick].ToString();
            return FetchStats(UserID);
        }

        
        public static string FetchStats(int UserID)
        {
            return GetUrlContents(String.Format("https://masterserver.hon.s2games.com/client_requester.php?f=get_all_stats&account_id[0]={0}", UserID));
        }


        public static string GetUrlContents(string Url)
        {
            var webRequest = (HttpWebRequest)WebRequest.Create(Url);
            webRequest.Method = "GET";

            var response = webRequest.GetResponse();

            string result;
            using (StreamReader sr = new StreamReader(response.GetResponseStream(), Encoding.UTF8))
            {
                result = sr.ReadToEnd();
            }

            return result;

        }
 

    }
}
